package cn.edu.sjtu.se.dslab.DAO.achieve;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.HibernateSystemException;

import cn.edu.sjtu.se.dslab.DAO.IUserDAO;
import cn.edu.sjtu.se.dslab.exception.DBException;
import cn.edu.sjtu.se.dslab.pojo.User;
import cn.edu.sjtu.se.dslab.util.DBMessage;

public class UserDAOAchieve extends BaseDAOAchieve<Object> implements IUserDAO {
	/**
	 * 定义日志处理对象
	 */
	private static final Log log = LogFactory.getLog(UserDAOAchieve.class);
	// property constants
	public static final String LOGINNAME = "loginname";
	public static final String USERPASSWORD = "userpassword";

	protected void initDao() {
		// do nothing
	}

	/**
	 * 按登录信息查询
	 * 
	 * @param 登录名
	 * @param 登录密码
	 * @return 系统用户
	 * @throws RuntimeException
	 */
	public User findByLoginInfo(String loginname, String password)
			throws DBException {
		log.debug("finding user instance with loginname: " + loginname
				+ ", password: " + password);
		try {
			// 定义存放hql语句的StringBuffer对象
			StringBuffer hql = new StringBuffer();

			// 拼接sql语句
			hql.append("from User s ");
			hql.append("where s.username='");
			hql.append(loginname);
			hql.append("' and s.password='");
			hql.append(password);
			hql.append("'");

			// 查询Systemuser表
			List<Object> users = find(hql.toString());

			// 验证是否正确
			if (users.size() > 0) {
				// 返回担当者信息
				return (User) users.get(0);
			} else {
				// 返回空
				return null;
			}
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	/**
	 * 按登录名查询
	 * 
	 * @param 登录名
	 * @return 系统用户
	 * @throws RuntimeException
	 */
	public User findByLoginname(String loginname) throws DBException {
		log.debug("finding User instance with loginname: " + loginname);
		try {
			// 定义存放hql语句的StringBuffer对象
			StringBuffer hql = new StringBuffer();

			// 拼接sql语句
			hql.append("from User ");
			hql.append("where username='");
			hql.append(loginname);
			hql.append("'");
			// 查询Systemuser表
			List<Object> users = find(hql.toString());

			// 验证是否正确
			if (users.size() > 0) {
				// 返回担当者信息
				return (User) users.get(0);
			} else {
				// 返回空
				return null;
			}
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	/**
	 * 获取查询hql语句
	 * 
	 * @return hql语句
	 */
	public String getAllHql() {
		// 定义返回值
		String hql = "from User";
		// 返回hql语句
		return hql;
	}

	/**
	 * 删除<BR>
	 * 
	 * @param 数据集
	 * @throws DBException
	 */
	public void delete(User obj) throws DBException {
		// 获得session对象
		Session session = getHibernateTemplate().getSessionFactory()
				.openSession();
		// 创建删除事务
		Transaction tx = null;
		try {
			// 开始一个事务
			tx = session.beginTransaction();
			// 执行事务
			User bean = (User) getHibernateTemplate().get(
					"cn.edu.sjtu.se.dslab.pojo.User", obj.getId());
			getHibernateTemplate().delete(bean);
			// 提交事务
			tx.commit();
		} catch (DataAccessResourceFailureException e) {
			if (tx != null) {// 出现异常则撤销事务
				tx.rollback();
			}
			// 如果连接数据库失败抛出DBException并且传入消息
			throw new DBException(DBMessage.DBCONNECT_RETRYOVER);
		} catch (HibernateSystemException e) {
			if (tx != null) {// 出现异常则撤销事务
				tx.rollback();
			}
			// 执行错误
			throw new DBException(DBMessage.EXECUTE_UPDATE);
		} catch (Exception e) {
			if (tx != null) {// 出现异常则撤销事务
				tx.rollback();
			}
			// 出现除以上情况的其它情况抛出异常对象
			throw new DBException(DBMessage.E_OTHER);
		} finally {
			try {
				// 关闭session
				session.close();
			} catch (Exception e) {
				// 如果连接数据库失败抛出DBException并且传入消息Code
				throw new DBException(DBMessage.DBCONNECT_RETRYOVER);
			}
		}
	}

	/**
	 * 修改系统用户信息
	 * 
	 * @param ModifyPwdActionBean
	 * @throws DBException
	 */
	public void update(User obj) throws DBException {

		// 获得session
		Session session = getHibernateTemplate().getSessionFactory()
				.openSession();
		// 定义事务对象
		Transaction tx = null;

		try {
			//开始一个事务
			tx = session.beginTransaction();
			//执行事务
			User sysUser = (User) getHibernateTemplate().get(
					"cn.edu.sjtu.se.dslab.pojo.User", obj.getId());
			//设置信息
			sysUser.setPassword(obj.getPassword());
			getHibernateTemplate().update(sysUser);
			//提交事务
			tx.commit();
		} catch (DataAccessResourceFailureException e) {
			if (tx != null) {//出现异常则撤销事务
				tx.rollback();
			}
			//如果连接数据库失败抛出DBException并且传入消息Code
			throw new DBException(DBMessage.DBCONNECT_RETRYOVER);
		} catch (IllegalArgumentException e) {
			if (tx != null) {//出现异常则撤销事务
				tx.rollback();
			}
			//如果执行出现问题抛出DBException并且传入消息
			throw new DBException(DBMessage.EXECUTE_UPDATE);
		} catch (Exception e) {
			if (tx != null) {//出现异常则撤销事务
				tx.rollback();
			}
			//出现除以上情况的其它情况抛出异常对象
			throw new DBException(DBMessage.E_OTHER);
		} finally {
			try {
				//关闭session
				session.close();
			}
			catch(Exception e)
			{
				//如果连接数据库失败抛出DBException并且传入消息Code
				throw new DBException(DBMessage.DBCONNECT_RETRYOVER);
			}
		}
	}

	/**
	 * 根据id查找用户
	 * @param systemuserId
	 * @throws DBException
	 */
	public User findUserById(Long Id) throws DBException {
		log.debug("finding user instance with Id: " + Id);
		try {
			//定义存放hql语句的StringBuffer对象
			StringBuffer hql = new StringBuffer();
			
			//拼接sql语句
			hql.append("from User ");
			hql.append("where id='");
			hql.append(Id);
			hql.append("'");
			//查询user表
			List<Object> systemusers = find(hql.toString());

			//验证是否正确
			if (systemusers.size() > 0) {
				//返回员工信息
				return (User) systemusers.get(0);
			} else {
				//返回空
				return null;
			}
		} catch (RuntimeException re) {
			log.error("find by property userid failed", re);
			throw re;
		}
	}

}
